/*
 *	基于plupload.full.min.js 上传文件
 * 在需要上传文件入口的页面中添加js组件
 * plupload.full.min.js  上传插件
 * upload-file.js        上传执行js
 * 上传ID=btn-upload-file
 */
$(function() {

    /*生成上传文件显示层*/
    $('body').append(''+
        '<div class="uploader-list-wrapper">'+
        '   <div class="uploader-list-title"><h6>上传完成</h6><div><a href="javascript:;" data-type="min" title="最小化"></a><a href="javascript:;" data-type="close" title="关闭"></a></div></div>'+
        '   <div class="uploader-list-header">'+
        '        <div class="file-name">文件名</div>'+
        '        <div class="file-size">大小</div>'+
        '        <div class="file-status">状态</div>'+
        '        <div class="file-info"></div>'+
        '   </div>'+
        '   <div class="uploader-list"></div>'+
        '   <div class="bottom">'+
        '       <input type="hidden" id="parent_hash" value="{$params[parent_hash]}"/>'+
        '       <a id="start-upload" class="layui-btn layui-btn-sm">开始上传</a>'+
        '   </div>'+
        '</div>')

    $('body').append('<div class="uploader-drag-show" style="position: fixed; background: rgba(255, 255, 255, 0.6); border: 3px dashed rgb(204, 204, 204); z-index: 1000000; color: rgb(153, 153, 153); font-size: 40px; text-align: center; overflow: hidden; top: 0px; left: 0px; height:100%; line-height: 930px; width:100%;pointer-events:none;display: none;">将文件拖拽至此区域，上传至当前显示的目录下。</div>');

    var _UW = $('.uploader-list-wrapper');  //上传弹层主结构
    var _uploading = false;  //上传中，关闭弹层会进行提示。

    window.onbeforeunload = function (e) {
        e = e || window.event;
        if(_uploading){
            // 兼容IE8和Firefox 4之前的版本
            if (e) {
              e.returnValue = '关闭提示';
            }
            // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
            return '关闭提示';
        }
    };



    // var json_file_aliases_string = '{$json_file_aliases}';
    // json_file_aliases = $.parseJSON(json_file_aliases_string);
    // var max_file_size = '{$max_file_size}';
    // var has_file_limit_rule = '{$has_file_limit_rule}';
    // var new_files = {};

	/*演示内容 begin*/
	var json_file_aliases_string = '["tsg_33009"]';
	json_file_aliases = $.parseJSON(json_file_aliases_string); 
	var max_file_size = '10000kb';
	var has_file_limit_rule = '{$has_file_limit_rule}';
	var new_files = {};
	/*end*/

    var file_types = {
        'text/plain': 'txt',
        'application/zip': 'zip',
        'application/msword': 'word',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'word',
        'application/vnd.ms-excel': 'excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'excel',
        'application/vnd.ms-excel': 'csv',
        'application/pdf': 'pdf',
        'application/kswps': 'pdf',
        'image/png': 'png',
        'image/jpeg': 'png',
    };
    var options = {
        browse_button: ['plupload-browse-button','plupload-browse-button-file'], // this can be an id of a DOM element or the DOM element itself
        runtimes: 'html5,flash,silverlight,html4',
        url: '/file/upload_new_amz/parent_hash/' + $('#parent_hash').val(),
        preventCaching: true,
        // User can upload no more then 20 files in one go (sets multiple_queues to false)
        max_file_count: 20,

        chunk_size: '10mb',

        // Rename files by clicking on their titles
        rename: true,

        // Sort files
        sortable: true,

        // Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
        dragdrop: true,

        // Views to activate
        views: {
            list: true,
            thumbs: true, // Show thumbs
            active: 'thumbs'
        },

        // Flash settings
        flash_swf_url: '/libs/plupload/Moxie.swf',

        // Silverlight settings
        silverlight_xap_url: '/libs/plupload/Moxie.xap',
        multipart_params: {
            total_size: 0,
        },
        drop_element : 'plupload-drag-area',//拖拽上传
        //解决本地中文乱码
        //unique_names:true
    };
    //类型过滤,文件尺寸
    if (max_file_size) {
        options.max_file_size = max_file_size;
    }

    var uploader = new plupload.Uploader(options);
    uploader.init();

    //当文件添加到上传队列后触发
    uploader.bind('FilesAdded', function(up, files) {
    	// console.log('加入上传队列',files)

        var file_aliases_string = ',' + json_file_aliases.join(',') + ',';
        var regex = /^[a-zA-Z0-9_#%\-\.\(\)&\u4e00-\u9fa5]+$/;
        for (var i in files) {
            if (!regex.test(files[i].name)) {
                layer.alert('文件名支持:中文、数字、字母、下划线、中划线、#、%、& 半角() .')
                // $.tip({ type: 'error', msg: '文件名支持:中文、数字、字母、下划线、中划线、#、%、& 半角() .' });
                uploader.removeFile(files[i]);
                delete(files[i]);
                continue;
            }
        }
        //当存在文件大小限制的时候
        //获取到队列中所有文件的总大小，如果队列中文件的总大小超过限定大小，
        //拒绝选择，并弹出错误提示 
        //start->add by zengrui 2016年11月23日13:51:15
        if (max_file_size) {
            var total_size = uploader.total.size;
            if (total_size > max_file_size) {
                var display_max_file_size = getUnit(max_file_size, 0);
                var display_uploaded_file_size = getUnit(total_size, 0);
                if (has_file_limit_rule) {
                    //移除队列中的所有待上传文件
                    for (var i in files) {
                        uploader.removeFile(files[i]);
                    }
                    layer.alert('您的剩余空间为' + display_max_file_size + ',当前批量上传文件总大小为:' + display_uploaded_file_size);

                    return false;
                } else {
                    //移除队列中的所有待上传文件
                    for (var i in files) {
                        uploader.removeFile(files[i]);
                    }
                    layer.alert('文件尺寸不能大于' + display_max_file_size + ',当前上传文件大小为:' + display_uploaded_file_size);
                    return false;
                }
            }
        }

		/*
		 *	添加上传文件进列表
		 */
        _UW.show().removeClass('min');//显示弹层
        for (var i in files) {
            // console.log('选择上传的文件',files[i]);

            var size = getUnit(files[i].size, 0);
            var file_type = file_types[files[i].type] ? file_types[files[i].type] : 'undefined';
            console.log(files[i])

            //添加文件时将当前文件的大小添加到选项参数中
            _UW.find(".uploader-list").append('<div id="' + files[i].id + '" class="file">' +
                '<ul>'+
                '<li class="file-name"><i class="file-icon '+file_type+'"></i>' + files[i].name + '</li>' +
                '<li class="file-size">' + size + '</li>' +
                '<li class="file-status">待上传</li>' +
                '<li class="file-info"><i class="file-remove layui-icon layui-icon-close"></i></li>' +
                '</ul>'+
                '<label class="progress"></label>'+
                '</div>');
            if (file_aliases_string.indexOf(',' + files[i].name) != -1) {
                uploader.removeFile(files[i].id);
                _UW.find('#' + files[i].id).find('.file-status').html('<i class="iconfont file-error">&#xe675;</i>');
                _UW.find('#' + files[i].id).find('.file-info').html('此文件已经存在!');
                _UW.find('#' + files[i].id).delay(2000).fadeOut(1000, function() {
                    $(this).remove();
                });

            } else {
                if (new_files[files[i].name] != undefined) {
                    _UW.find('#' + files[i].id).find('.file-status').html('<i class="iconfont file-error">&#xe675;</i>');
                    _UW.find('#' + files[i].id).find('.file-info').html('此文件已经存在!');
                    _UW.find('#' + files[i].id).delay(2000).fadeOut(1000, function() {
                        $(this).remove();
                    });
                    uploader.removeFile(files[i].id);
                    //return false;
                } else {
                    new_files[files[i].name] = files[i].name;
                }
            }
        }
        console.log('★添加上传文件个数：',files.length)
    });

    //当文件从上传队列移除后触发
    uploader.bind('FilesRemoved', function(up, file) {
        //console.log('★自动移除了上传队列',file)
        var num = 0;
        up.files.map(function(d,i){
            if(d.status === 1){
                num++;
            }
        })
        console.log('★待上传文件数：',num)
        if(num == 0){
            _UW.find('.uploader-list-title h6').html('上传文件');
        }else{
            _UW.find('.uploader-list-title h6').html('待上传文件'+num+'个');
        }
    });
    
    //当上传队列发生变化后触发，即上传队列新增了文件或移除了文件。QueueChanged事件会比FilesAdded或FilesRemoved事件先触发
    uploader.bind('QueueChanged',function(up){
        console.log('★上传队列发生变化，总数：',up.files.length)
        _UW.find('.uploader-list-title h6').html('待上传文件数：'+ up.files.length +'个');
        var num = 0;
        up.files.map(function(d,i){
            if(d.status === 1){
                num++;
            }
        })
        if(num == 0){
            _UW.find('.uploader-list-title h6').html('上传文件');
        }else{
            _UW.find('.uploader-list-title h6').html('待上传文件'+num+'个');
        }
    })

    //当队列中的某一个文件上传完成后触发
    uploader.bind('FileUploaded', function(up, file, result) {
        if (uploader.total.percent == 100) {
            //window.location.reload();
        }
        var response = $.parseJSON(result.response);
        if ('false' === response.success) {
            layer.alert(response.message);
            return false;
        }
        console.log(result);
    })

    //所有文件上传后
    uploader.bind('UploadComplete', function(up, files) {
        _UW.find('.uploader-list-title h6').html('上传完成');
        _uploading = false;
        //刷新页面中的表格
        layui.table.reload('file-table',{
            whree:{
            },
            page:{
                curr:1
            }
        })
    });
    //上传文件之前，将传递给后端的文件总大小，动态改变为当前正在上传的文件的大小
    //start->add by zengrui
    uploader.bind('BeforeUpload', function(up, file) {
        options.multipart_params.total_size = file.size;
        options.multipart_params.file_name = file.name;
    });
    //end->by zengrui

    uploader.bind('UploadProgress', function(uploader, file) {
        _UW.find('#' + file.id).find('.progress').css({ "width": file.percent + "%" });
        _UW.find('#' + file.id).find('.file-info').html(file.percent + "%");
        if (file.percent == 100) {
            _UW.find('#' + file.id).find('.file-status').html('<i class="iconfont file-ok">&#xe643;</i>');
            _UW.find('#' + file.id).find('.progress').css({opacity:0});
        }
    });

    uploader.bind('ChunkUploaded', function(up, file, response) {
        var data = $.parseJSON(response.response);
        console.log(data);

        if (data['chunk'] == '0' && typeof(data.sign) != 'undefined') {}
    });

    uploader.bind('OptionChanged', function() {

    });
    uploader.bind('Error', function(up, err) {
        console.log('上传error')
        if (err.code == -600) {
            //获取错误关联文件相关信息
            var display_file_size = getUnit(max_file_size, 0);
            var current_file = err.file;
            var current_file_size = getUnit(current_file.size, 0);

            if (has_file_limit_rule) {
                //当有文件上传活动规则的时候的提示信息 add by zengrui 
                layer.alert('您的剩余空间为' + display_file_size + ',当前文件尺寸为:' + current_file_size);
            } else {
                layer.alert('文件尺寸不能大于' + max_file_size + '当前文件尺寸为:' + current_file_size);
            }

        } else {
            layer.alert(err.code + ':' + err.message);
        }
    });

    //开始上传
    $(document).on('click','#start-upload',function(){
        //上传前处理下，有待上传的才执行下去
        var flag = false;
        for(var i in uploader.files){
            if(uploader.files[i].status == 1 || uploader.files[i].status == 2) flag = true;
        }
        if(!flag) return false;
        uploader.start();
        _UW.find('.uploader-list-title h6').html('正在上传');
        _uploading = true;
    });

    //从上传列表中移除文件
    $(document).on('click','.file-remove', function() {
        var file_id = $(this).parents('.file').attr('id');
        var file_name = $(this).parents('.file').find('.file-name').text();
        delete(new_files[file_name]);
        uploader.removeFile(file_id);
        $(this).parents('.file').remove();
    });

    function getUnit(size, index) {
        var units = new Array('BYTE', 'KB', 'MB', 'GB');
        if (size < 1024) {
            return size.toFixed(2) + ' ' + units[index];
        }
        if (size >= 1024) {
            return getUnit(size / 1024, ++index);
        }
    }

    //拖拽上传
    // //阻止浏览器默认行为
    // document.addEventListener( "dragleave", function(e) {
    //      e.preventDefault();
    // }, false);
    // document.addEventListener( "drop", function(e) {
    //      e.preventDefault();
    // }, false);
    // document.addEventListener( "dragenter", function(e) {
    //      e.preventDefault();
    // }, false);
    // document.addEventListener( "dragover", function(e) {
    //      e.preventDefault();
    // }, false);
    var lastenter = null;
    var dragArea = document.getElementById('plupload-drag-area');
    if(dragArea !== null){
        dragArea.addEventListener("dragenter", function (e) {
            lastenter = e.target;
            $('.uploader-drag-show').show();
        },false);
        dragArea.addEventListener("drop", function (e) {
            $('.uploader-drag-show').hide();
        }, false);
        dragArea.addEventListener("dragleave", function (e) {
            if(lastenter === e.target){
                console.log('dragleave')
                $('.uploader-drag-show').hide();
            }
        },false);
    }

    /*
     *  弹层head操作事件
     */
    $(document).on('click','.uploader-list-title a',function(){
        var _this = $(this),
            type = $(this).data('type');
        switch (type) {
            case 'min'://最小化
                if(_UW.hasClass('min')){
                    _UW.removeClass('min');
                }else{
                    _UW.addClass('min');
                }
                break;
            case 'close'://关闭弹层
                console.log('★是否上传中',_uploading)
                if(_uploading){
                    layer.confirm('文件正在上传中，关闭会终止上传。',function(index){
                        clearUp();
                        layer.close(index);
                    })
                }else{
                    clearUp();
                }
                function clearUp(){
                    //清空上传列表
                    _UW.find('.uploader-list .file').map(function(i,d){
                        uploader.removeFile($(d).attr('id'));
                    })
                    for(var key in new_files){
                        delete new_files[key];
                    }
                    _UW.hide();
                    _UW.find('.uploader-list').html('');
                    _uploading = false;                 
                }
                break;
        }
    })
});